package models

import (
	"context"
	"fmt"
	"time"

	"github.com/ClickHouse/clickhouse-go/v2/lib/driver"
	"github.com/shopspring/decimal"
)

type Realtime struct {
	Symbol    string          `ch:"symbol" json:"symbol"`       // 股票代码
	Timestamp time.Time       `ch:"timestamp" json:"timestamp"` // 时间戳，精确到毫秒
	Open      decimal.Decimal `ch:"open" json:"open"`           // 开盘价
	High      decimal.Decimal `ch:"high" json:"high"`           // 最高价
	Low       decimal.Decimal `ch:"low" json:"low"`             // 最低价
	Close     decimal.Decimal `ch:"close" json:"close"`         // 收盘价/现价
	Volume    int64           `ch:"volume" json:"volume"`       // 成交量
	Amount    decimal.Decimal `ch:"amount" json:"amount"`       // 成交额
}

type RealtimeModel struct {
	ctx        context.Context
	clickhouse driver.Conn
}

func NewRealtimeModel(ctx context.Context, clickhouse driver.Conn) *RealtimeModel {
	return &RealtimeModel{ctx: ctx, clickhouse: clickhouse}
}

// TableName 表名
func (RealtimeModel) TableName() string {
	return "realtime"
}

func (r RealtimeModel) Insert(realtime *Realtime) error {
	err := r.clickhouse.Exec(r.ctx,
		"INSERT INTO realtime (symbol, timestamp, open, high, low, close, volume, amount) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
		realtime.Symbol, realtime.Timestamp, realtime.Open, realtime.High, realtime.Low, realtime.Close, realtime.Volume, realtime.Amount)
	if err != nil {
		return fmt.Errorf("insert realtime data error: %v", err)
	}

	return nil
}
